/**
 * 微信端公共的js
 */
var commUtils = (function () {

    var ajax_flag = false;//异步请求标志
    var rootpath;

    /**
     * 获得项目根路径
     */
    function getContextRootPath() {
        if (!isEmpty(rootpath)) {
            return rootpath;
        }
        var webroot = document.location.href;
        var webroot1 = webroot.substring(0, webroot.indexOf('//') + 2);
        webroot = webroot.substring(webroot.indexOf('//') + 2, webroot.length);
        var webroot2 = webroot.substring(0, webroot.indexOf('/') + 1);
        webroot = webroot.substring(webroot.indexOf('/') + 1, webroot.length);
        webroot = webroot.substring(0, webroot.indexOf('/'));
        rootpath = webroot1 + webroot2;
        return rootpath;
    }

    /**
     * ajax  方法
     * @param {请求地址} url
     * @param {请求参数} params
     * @param {返回数据类型  "json"or"html"} dType
     * @param {回调函数} callback
     * @param {载入提示信息} loadingMsg
     */
    function ajax$(url, params, dType, callback, loadingMsg) {
        if (!ajax_flag) {//防止重复请求
            ajax_flag = true;
            //showLoadingMsg();
            $.ajax({
                url: url,
                data: params,
                type: "post",
                dataType: dType,
                async: false,
                success: function (data) {
                    ajax_flag = false;
                    //hideLoadingMsg();
                    if (typeof callback !== 'function') {
                        callback = defaultFn;
                    }
                    callback(data);
                },
                error: function () {
                    ajax_flag = false;
                    //hideLoadingMsg();
                }
            });
        }
    }

    /**
     * 判断是否为空，"",null,undefined
     */
    function isEmpty(value) {
        return 'undefined' === typeof value || null === value || "" === value || "null" === value;
    }

    /**
     * 获取url后面参数
     */
    function GetArgsFromHref(sHref, sArgName) {
        var args = sHref.split("?");
        var retval = "";

        if (args[0] == sHref) {
            return retval;
        }
        var str = args[1];
        args = str.split("&");
        for (var i = 0; i < args.length; i++) {
            str = args[i];
            var arg = str.split("=");
            if (arg.length <= 1)
                continue;
            if (arg[0] == sArgName)
                retval = decodeURI(arg[1]);
        }
        return retval;
    }

    /**
     * 默认回调函数
     */
    function defaultFn() {

    }

    function showLoadingMsg() {
        //$.showLoading();
    }

    function hideLoadingMsg() {
        $(".weui_mask_transparent").remove();
        $(".weui_toast").remove();
    }


    //验证手机
    function checkMobile(value) {
        if (commUtils.isEmpty(value)) {
            return false;
        }
        var length = value.length;
        var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
        return length == 11 && mobile.test(value);
    }

    return {
        getContextRootPath: getContextRootPath,
        ajax$: ajax$,
        isEmpty: isEmpty,
        GetArgsFromHref: GetArgsFromHref,
        checkMobile: checkMobile
    }
}());

/**
 * 限制输入框可输入文字
 * @type {{registerIntNumberInput, registerDecimalNumberInput, registerInputLimits}}
 */
var inputUtils = (function () {
    var registerIntNumberInput = function ($obj) {
        registerEventListeners($obj, intNumberInputCallBack);
    };
    var registerDecimalNumberInput = function ($obj) {
        registerEventListeners($obj, decimalNumberInputCallBack);
    };

    var registerInputLimits = function ($obj, callBack) {
        registerEventListeners($obj, callBack);
    };

    var registerEventListeners = function ($obj, callBack) {
        $obj.on("input", callBack);
    };

    function intNumberInputCallBack() {
        intNumberOnly($(this));
    }

    function decimalNumberInputCallBack() {
        decimalOnly($(this));
    }

    function intNumberOnly($obj) {
        filterString($obj, /\D/g)
    }

    function decimalOnly($obj) {
        filterString($obj, /[^\d.-]/g)
    }

    function filterString($obj, regex) {
        var value = $obj.val();
        $obj.val(value.replace(regex, ''));
    }

    return {
        intNumberOnly: intNumberOnly,
        decimalOnly: decimalOnly,
        registerIntNumberInput: registerIntNumberInput,
        registerDecimalNumberInput: registerDecimalNumberInput,
        registerInputLimits: registerInputLimits
    }
}());

/**
 * 支持byte 数据接收处理
 */
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
        return {
            // create new XMLHttpRequest
            send: function (headers, callback) {
                // setup all variables
                var xhr = new XMLHttpRequest(),
                    url = options.url,
                    type = options.type,
                    async = options.async || true,
                    // blob or arraybuffer. Default is blob
                    dataType = options.responseType || "blob",
                    data = options.data || null,
                    username = options.username || null,
                    password = options.password || null;

                xhr.addEventListener('load', function () {
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

                // setup custom headers
                for (var i in headers) {
                    xhr.setRequestHeader(i, headers[i]);
                }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function () {
                jqXHR.abort();
            }
        };
    }
});